import form
import listentry
import uix
import uiutil
import uthread
import util
import xtriui
import blue
import uiconst
import uicls

class CorpRecruitment(uicls.Container):
    __guid__ = 'form.CorpRecruitment'
    __nonpersistvars__ = []
    __notifyevents__ = ['OnJoinLeaveChannel']

    def init(self):
        sm.RegisterNotify(self)



    def Load(self, args):
        if not self.sr.Get('inited', 0):
            self.sr.inited = 1
            self.InitFilters()
            self.toolbarContainerForCorp = uicls.Container(name='toolbarContainerForCorp', align=uiconst.TOBOTTOM, parent=self)
            btns = [[mls.UI_CMD_ADD,
              self.CorpViewRecruitment,
              (None,),
              None]]
            btns = uix.MakeBtnGroup(btns, where=self.toolbarContainerForCorp)
            self.toolbarContainerForCorp.height = btns.height
            self.toolbarContainerForAll = uicls.Container(name='toolbarContainerForAll', align=uiconst.TOTOP, parent=self, left=const.defaultPadding, top=const.defaultPadding)
            regions = []
            for each in sm.GetService('map').GetMapCache()['hierarchy'].iterkeys():
                if util.IsWormholeRegion(each):
                    continue
                regions.append((cfg.evelocations.Get(each).name, each))
                continue

            regions.sort(lambda a, b: cmp(a[0], b[0]))
            preselectedRegion = settings.char.ui.Get('corporation_recruitment_regionid', eve.session.regionid)
            if util.IsWormholeRegion(preselectedRegion):
                preselectedRegion = regions[0][0]
            toppush = (const.defaultPadding + 10)
            self.sr.filter_region = uicls.Combo(label=mls.UI_GENERIC_REGION, parent=self.toolbarContainerForAll, options=regions, name='corporation_recruitment_regionid', select=preselectedRegion, callback=self.ComboChange, pos=((const.defaultPadding + 1),
             toppush,
             0,
             0), width=112)
            skills = [(mls.UI_CORP_LIMITBYSKILLSNOT, 0), (mls.UI_CORP_LIMITBYSKILLS, 1)]
            self.sr.filter_skills = uicls.Combo(label=mls.UI_GENERIC_SKILLPOINTS, parent=self.toolbarContainerForAll, options=skills, name='corporation_recruitment_skillpoints', select=settings.char.ui.Get('corporation_recruitment_skillpoints', 1), callback=self.ComboChange, pos=(((self.sr.filter_region.left + self.sr.filter_region.width) + 4),
             toppush,
             0,
             0), width=112)
            alliances = [(mls.UI_CORP_ISINALLIANCENOT, 0), (mls.UI_CORP_ISINALLIANCE, 1)]
            self.sr.filter_alliances = uicls.Combo(label=mls.UI_GENERIC_ALLIANCE, parent=self.toolbarContainerForAll, options=alliances, name='corporation_recruitment_isinalliance', select=settings.char.ui.Get('corporation_recruitment_isinalliance', 1), callback=self.ComboChange, pos=(((self.sr.filter_skills.left + self.sr.filter_skills.width) + 4),
             toppush,
             0,
             0), width=112)
            self.sr.filter_minmembers = uicls.SinglelineEdit(name='corporation_recruitment_minmembers', parent=self.toolbarContainerForAll, setvalue=settings.char.ui.Get('corporation_recruitment_minmembers', 1), label=mls.UI_GENERIC_MIN, left=((self.sr.filter_alliances.left + self.sr.filter_alliances.width) + 4), width=42, top=toppush, ints=(0, 10000))
            self.sr.filter_maxmembers = uicls.SinglelineEdit(name='corporation_recruitment_maxmembers', parent=self.toolbarContainerForAll, setvalue=settings.char.ui.Get('corporation_recruitment_maxmembers', 100000), label=mls.UI_GENERIC_MAX, left=((self.sr.filter_minmembers.left + self.sr.filter_minmembers.width) + 4), width=42, top=toppush, ints=(0, 10000))
            self.sr.filter_maxmembers.sr.hint = self.sr.filter_minmembers.sr.hint = mls.UI_CORP_MEMBERLIMIT
            icon = xtriui.BaseButton(uicls.Sprite(parent=self.toolbarContainerForAll, width=20, height=20, align=uiconst.BOTTOMRIGHT, top=0, left=6))
            icon.texture.pixels = 'res:/UI/Texture/UITexLib_03.dds'
            icon.rectWidth = icon.rectHeight = 20
            icon.rectTop = 0
            icon.rectLeft = 144
            icon.hint = mls.UI_GENERIC_REFRESH
            icon.Click = self.LoadAllAdverts
            self.toolbarContainerForAll.height = ((self.sr.filter_region.height + const.defaultPadding) + 10)
            self.sr.scroll = uicls.Scroll(name='recruitment', parent=self, padding=(const.defaultPadding,
             const.defaultPadding,
             const.defaultPadding,
             const.defaultPadding))
            self.sr.scroll.sr.id = 'corp_recruitment_adverts'
            self.sr.scroll.sr.fixedColumns = {mls.UI_CORP_LOGO: 44}
            self.sr.scroll2 = uicls.Scroll(name='recruitmentsettings', parent=self, padding=(const.defaultPadding,
             const.defaultPadding,
             const.defaultPadding,
             const.defaultPadding))
            tabs = []
            if ((not util.IsNPC(eve.session.corpid)) and ((session.corprole & const.corpRolePersonnelManager) == const.corpRolePersonnelManager)):
                tabs.append([mls.UI_CORP_OURADVERTS,
                 self.sr.scroll,
                 self,
                 'corp'])
            tabs.append([mls.UI_CORP_OTHERADVERTS,
             self.sr.scroll,
             self,
             'all'])
            tabs.append([mls.UI_GENERIC_FILTERINGOPTIONS,
             self.sr.scroll2,
             self,
             'filter'])
            tabs = form.TabGroup(uicls.Container(name='tabparent', align=uiconst.TOTOP, height=18, parent=self, idx=0)).Startup(tabs, 'corporationrecruitment', UIIDPrefix='corporationRecruitmentTab')
            self.sr.tabs = tabs
        self.SetHint()
        if not self.sr.Get('displayMode'):
            self.sr.displayMode = None
        if not self.sr.Get('viewingOwnerID'):
            self.sr.displayMode = None
        subcaption = ''
        if (args == 'all'):
            self.sr.viewingOwnerID = -1
            self.ShowAllAdverts()
            subcaption = mls.UI_CORP_DELAYED5MINUTES
        elif (args == 'corp'):
            self.sr.viewingOwnerID = eve.session.corpid
            self.ShowCorpAdverts()
            if not len(sm.GetService('corp').GetMyCorporationsOffices()):
                subcaption = mls.UI_CORP_HINT44
        elif (args == 'filter'):
            self.ShowCorpSettings()
        sm.GetService('corpui').LoadTop('07_08', mls.UI_CORP_RECRUITMENT, subcaption)



    def _OnClose(self):
        sm.UnregisterNotify(self)



    def OnJoinLeaveChannel(self, channelID, *args):
        if (self and (not self.destroyed)):
            for node in self.sr.scroll.GetNodes():
                if (node.Get('channelID', None) == channelID):
                    if node.panel:
                        node.panel.Load(node)




    def InitFilters(self):
        if (settings.char.ui.Get('corporation_recruitment_races', None) is None):
            settings.char.ui.Set('corporation_recruitment_races', (((const.raceCaldari + const.raceMinmatar) + const.raceGallente) + const.raceAmarr))
        if (settings.char.ui.Get('corporation_recruitment_types', None) is None):
            settings.char.ui.Set('corporation_recruitment_types', sum([ each.typeMask for each in sm.GetService('corp').GetRecruitmentAdTypes() ]))



    def OnClose_(self, *args):
        if not self.destroyed:
            if self.sr.Get('inited', 0):
                settings.char.ui.Set('corporation_recruitment_minmembers', self.sr.filter_minmembers.GetValue())
                settings.char.ui.Set('corporation_recruitment_maxmembers', self.sr.filter_maxmembers.GetValue())



    def LoadAllAdverts(self, *args):
        self.sr.viewingOwnerID = -1
        self.ShowAllAdverts()



    def GetRecruitmentAds(self, corporationID = None, regionID = None, skillPoints = 0, typeMask = 0, raceMask = 0, isInAlliance = False, minMembers = 0, maxMembers = 0, *args):
        ads = []
        if (eve.session.corpid and ((corporationID is None) and (regionID is None))):
            ads = sm.GetService('corp').GetRecruitmentAdsForCorporation()
        elif (regionID is not None):
            ads = sm.RemoteSvc('corporationSvc').GetRecruitmentAdsByCriteria(regionID, skillPoints, typeMask, raceMask, isInAlliance, minMembers, maxMembers)
        ownersToPrime = []
        for ad in ads:
            if ad.corporationID:
                ownersToPrime.append(ad.corporationID)
            if ad.allianceID:
                ownersToPrime.append(ad.allianceID)

        if ownersToPrime:
            cfg.eveowners.Prime(ownersToPrime)
        return ads



    def __GetLabel(self, advert):
        adCorp = cfg.eveowners.GetIfExists(advert.corporationID)
        adAlli = cfg.eveowners.GetIfExists(advert.allianceID)
        if (advert.expiryDateTime > blue.os.GetTime()):
            t = ('<color=0xff00FF00>%s<color=0xffffffff>' % mls.UI_GENERIC_ACTIVE)
        else:
            t = ('<color=0xFFEB3700>%s<color=0xffffffff>' % mls.UI_GENERIC_EXPIRED)
        label = ('%s<t>%s<t>%s<t>%s<t>%s' % (t,
         (getattr(adCorp, 'name', False) or mls.UI_GENERIC_UNKNOWN),
         (getattr(adAlli, 'name', False) or mls.UI_GENERIC_UNKNOWN),
         cfg.evelocations.Get(advert.regionID).name,
         cfg.evelocations.Get(advert.stationID).name))
        return label



    def __GetLabel2(self, advert):
        import blue
        adCorp = cfg.eveowners.GetIfExists(advert.corporationID)
        adAlli = cfg.eveowners.GetIfExists(advert.allianceID)
        if (advert.expiryDateTime < blue.os.GetTime()):
            t = ('<color=0xFFEB3700>%s</color>' % mls.UI_GENERIC_EXPIRED)
        else:
            t = util.FmtDate(advert.expiryDateTime)
        label = ('%s<t>%s<t>%s<t>%s<t>%s<t>%s' % ('',
         t,
         (getattr(adCorp, 'name', False) or mls.UI_GENERIC_NONE),
         (getattr(adAlli, 'name', False) or mls.UI_GENERIC_NONE),
         cfg.evelocations.Get(advert.regionID).name,
         cfg.evelocations.Get(advert.stationID).name))
        return label



    def ShowCorpSettings(self, *args):
        self.toolbarContainerForCorp.state = uix.UI_HIDDEN
        self.toolbarContainerForAll.state = uix.UI_HIDDEN
        if not getattr(self, 'settingsinited', 0):
            headers = []
            scrolllist = []
            races = [ each for each in sm.GetService('cc').GetData('races') if (each.raceID in [const.raceCaldari,
             const.raceMinmatar,
             const.raceGallente,
             const.raceAmarr]) ]
            scrolllist.append(listentry.Get('Subheader', {'label': mls.UI_GENERIC_RACES}))
            for race in races:
                text = Tr(race.raceName, 'character.races.raceName', race.dataID)
                checkboxSettingID = settings.char.ui.Get('corporation_recruitment_races', 0)
                data = util.KeyVal()
                data.label = (text + ((' (%s)' % mls.UI_GENERIC_YOU) if (eve.session.raceID == race.raceID) else ''))
                data.checked = ((race.raceID & checkboxSettingID) == race.raceID)
                data.cfgname = 'corporation_recruitment_races'
                data.retval = race.raceID
                data.OnChange = self.CheckBoxChange
                scrolllist.append(listentry.Get('Checkbox', data=data))

            scrolllist2 = []
            lastHeader = ''
            adTypes = sm.GetService('corp').GetRecruitmentAdTypes()
            for adType in adTypes:
                if (lastHeader != adType.groupName):
                    if (len(scrolllist2) == 1):
                        scrolllist2 = scrolllist2[2:]
                        lastHeader = ''
                    lastHeader = adType.groupName
                    scrolllist2.append(listentry.Get('Subheader', {'label': lastHeader}))
                text = adType.typeName
                checkboxSettingID = settings.char.ui.Get('corporation_recruitment_types', 0)
                data = util.KeyVal()
                data.label = text
                data.checked = ((adType.typeMask & checkboxSettingID) == adType.typeMask)
                data.cfgname = 'corporation_recruitment_types'
                data.retval = adType.typeMask
                data.OnChange = self.CheckBoxChange
                scrolllist2.append(listentry.Get('Checkbox', data=data))

            scrolllist += scrolllist2
            self.sr.scroll2.ShowHint()
            self.sr.scroll2.Load(contentList=scrolllist, headers=headers)
            if not scrolllist:
                self.sr.scroll2.ShowHint(mls.UI_CORP_NOMATCHESWITHFILTER)
            self.settingsinited = 1



    def CheckBoxChange(self, checkbox):
        key = checkbox.data['key']
        val = checkbox.data['retval']
        if (key in ('corporation_recruitment_races', 'corporation_recruitment_types')):
            cval = settings.char.ui.Get(key, 0)
            hasValue = ((val & cval) == val)
            if (checkbox.checked and (not hasValue)):
                cval += val
            elif hasValue:
                cval -= val
            settings.char.ui.Set(key, cval)



    def ComboChange(self, combo, header, value, *args):
        settings.char.ui.Set(combo.name, value)



    def ShowTestCorpAdverts(self, *args):
        self.ShowCorpAdverts(True)



    def ShowCorpAdverts(self, test = False, *args):
        self.sr.displayMode = 'edit'
        access = self.HasAccess(eve.session.corpid, 1)
        self.toolbarContainerForCorp.state = (uix.UI_NORMAL if access else uix.UI_HIDDEN)
        self.toolbarContainerForAll.state = uix.UI_HIDDEN
        adverts = self.GetRecruitmentAds()
        (scrolllist, headers,) = self.GetAdvertScrollEntries(adverts)
        self.sr.scroll.Load(contentList=scrolllist, headers=headers, noContentHint=mls.UI_CORP_NOADVERTS)



    def ShowAllAdverts(self, *args):
        self.sr.displayMode = 'view'
        self.toolbarContainerForCorp.state = uix.UI_HIDDEN
        self.toolbarContainerForAll.state = uix.UI_NORMAL
        ret_regionid = self.sr.filter_region.GetValue()
        ret_skillpoints = self.sr.filter_skills.GetValue()
        if ret_skillpoints:
            ret_skillpoints = sm.GetService('skills').GetSkillPoints()
        else:
            ret_skillpoints = 500000000
        ret_typemask = settings.char.ui.Get('corporation_recruitment_types', 0)
        ret_racemask = settings.char.ui.Get('corporation_recruitment_races', 0)
        ret_isinalliance = self.sr.filter_alliances.GetValue()
        ret_minmembers = self.sr.filter_minmembers.GetValue()
        ret_maxmembers = self.sr.filter_maxmembers.GetValue()
        adverts = self.GetRecruitmentAds(None, ret_regionid, ret_skillpoints, ret_typemask, ret_racemask, ret_isinalliance, ret_minmembers, ret_maxmembers)
        self.sr.scroll.ShowHint()
        (scrolllist, headers,) = self.GetAdvertScrollEntries(adverts)
        self.sr.scroll.Load(contentList=scrolllist, headers=headers)
        if not scrolllist:
            self.sr.scroll.ShowHint(mls.UI_CORP_NOMATCHESWITHFILTER)



    def GetAdvertScrollEntries(self, adverts, *args):
        scrolllist = []
        headers = []
        if adverts:
            headers = [mls.UI_CORP_LOGO,
             mls.UI_GENERIC_EXPIRES,
             mls.UI_GENERIC_CORPORATION,
             mls.UI_GENERIC_ALLIANCE,
             mls.UI_GENERIC_REGION,
             mls.UI_GENERIC_STATION]
            corpIDs = []
            for advert in adverts:
                corpIDs.append(advert.corporationID)

            corpIDs = list(set(corpIDs))
            cfg.eveowners.Prime(corpIDs)
            cfg.corptickernames.Prime(corpIDs)
            for advert in adverts:
                data = util.KeyVal()
                data.id = advert.adID
                data.label = self._CorpRecruitment__GetLabel2(advert)
                data.advert = advert
                data.OnDblClick = self._CorpViewRecruitment
                data.GetMenu = self.CorpViewRecruitmentMenu
                data.corporationID = advert.corporationID
                data.allianceID = advert.allianceID
                data.channelID = advert.channelID
                scrolllist.append(listentry.Get('RecruitmentEntry', data=data))

        return (scrolllist, headers)



    def CorpViewRecruitmentMenu(self, entry, *args):
        if self.destroyed:
            return 
        m = []
        if entry.sr.node.advert:
            if util.IsCorporation(entry.sr.node.corporationID):
                m += [(mls.UI_GENERIC_CORPORATION, sm.GetService('menu').GetMenuFormItemIDTypeID(entry.sr.node.corporationID, const.typeCorporation))]
            if util.IsAlliance(entry.sr.node.allianceID):
                m += [(mls.UI_GENERIC_ALLIANCE, sm.GetService('menu').GetMenuFormItemIDTypeID(entry.sr.node.allianceID, const.typeAlliance))]
            if m:
                m += [None]
            stationID = entry.sr.node.advert.stationID
            stationInfo = sm.GetService('ui').GetStation(stationID)
            m += [(mls.UI_CMD_LOCATION, sm.GetService('menu').CelestialMenu(entry.sr.node.advert.stationID, typeID=stationInfo.stationTypeID, parentID=stationInfo.solarSystemID))]
            m += [None]
            m += [(mls.UI_CMD_VIEW,
              self._CorpViewRecruitment,
              (entry))]
            if self.HasAccess(entry.sr.node.corporationID):
                if (entry.sr.node.advert.expiryDateTime > blue.os.GetTime()):
                    m += [(mls.UI_CMD_EDIT,
                      self._CorpEditRecruitment,
                      (entry))]
                m += [(mls.UI_CMD_REMOVE,
                  self.DeleteRecruitmentAd,
                  (entry.sr.node.advert))]
            return m



    def DeleteRecruitmentAd(self, advert):
        if self.destroyed:
            return 
        if not self.HasAccess(advert.corporationID):
            return 
        if (eve.Message('CorpAdsAreYouSureYouWantToDelete', None, uix.YESNO, suppress=uix.ID_YES) == uix.ID_YES):
            sm.GetService('corp').DeleteRecruitmentAd(advert.adID)



    def SetHint(self, hintstr = None):
        self.sr.scroll.ShowHint(hintstr)



    def OnCorporationRecruitmentAdChanged(self, corporationID, adID, change):
        uix.LogInfo('OnCorporationRecruitmentAdChanged corporationID', corporationID, 'adID', adID, 'change', change)
        if ((self is None) or self.destroyed):
            uix.LogInfo('OnCorporationRecruitmentAdChanged self is None or self.destroyed')
            return 
        if ((not self.sr.Get('scroll')) or (self.sr.scroll is None)):
            uix.LogInfo('OnCorporationRecruitmentAdChanged no scroll')
            return 
        bAdd = 0
        bRemove = 0
        if change:
            bAdd = 1
            bRemove = 1
            for (old, new,) in change.itervalues():
                if ((old is None) and (new is None)):
                    continue
                if (old is not None):
                    bAdd = 0
                if (new is not None):
                    bRemove = 0

            if (bAdd and bRemove):
                raise RuntimeError('recruitment::OnCorporationRecruitmentAdChanged WTF')
        recruitment = None
        if not bRemove:
            if (eve.session.corpid == corporationID):
                recruitment = self.GetRecruitmentAds()
            if (recruitment is not None):
                if (corporationID == eve.session.corpid):
                    self.sr.tabs.BlinkPanelByName(mls.UI_CORP_OURADVERTS)
        if (self.sr.viewingOwnerID == eve.session.corpid):
            self.Load('corp')
        elif (self.sr.viewingOwnerID == -1):
            self.Load('all')



    def HasAccess(self, corporationID, officeCheck = 0):
        if (corporationID == eve.session.corpid):
            if ((const.corpRolePersonnelManager & eve.session.corprole) != const.corpRolePersonnelManager):
                return False
            else:
                if (officeCheck and (not len(sm.GetService('corp').GetMyCorporationsOffices()))):
                    return False
                return True
            return False



    def _CorpViewRecruitment(self, entry, *args):
        self.sr.displayMode = 'view'
        self.CorpViewRecruitment(entry)



    def _CorpEditRecruitment(self, entry, *args):
        self.sr.displayMode = 'edit'
        self.CorpViewRecruitment(entry)



    def CorpViewRecruitment(self, entry, *args):
        corpid = None
        advert = None
        if (entry is not None):
            corpid = entry.sr.node.Get('corporationID', None)
            advert = entry.sr.node.Get('advert', None)
        else:
            self.sr.displayMode = 'add'
        isEditable = False
        if (corpid is None):
            corpid = eve.session.corpid
            advert = util.KeyVal()
            advert.raceMask = 0
            advert.typeMask = 0
            advert.skillPoints = 0
            advert.description = None
            advert.channelID = None
            advert.stationID = None
        corpid = (corpid if (corpid is not None) else eve.session.corpid)
        if self.HasAccess(corpid):
            isEditable = True
        wnd = sm.GetService('window').GetWindow('createcorpad')
        if wnd:
            wnd.SelfDestruct()
        sm.GetService('window').GetWindow('createcorpad', 1, decoClass=form.CreateAdvert, advert=advert, displayMode=self.sr.displayMode)




class RecruitmentEntry(listentry.Generic):
    __guid__ = 'listentry.RecruitmentEntry'
    __params__ = ['corporationID']

    def Startup(self, *args):
        listentry.Generic.Startup(self, *args)
        self.sr.infoicon = uicls.InfoIcon(size=16, left=0, top=2, parent=self, idx=0, align=uiconst.TOPRIGHT)
        self.sr.infoicon.OnClick = self.ShowInfo
        self.sr.corpicon = uicls.Container(parent=self, width=32, height=32, left=4, top=1, align=uiconst.TOPLEFT)
        self.joinleaveBtn = uicls.Button(parent=self, label=mls.UI_CMD_JOIN, pos=(20, 0, 0, 0), func=self.JoinLeaveChannel, idx=0, align=uiconst.CENTERRIGHT)
        self.id = 'test'



    def Load(self, node):
        listentry.Generic.Load(self, node)
        self.sr.node = node
        data = node
        self.corporationID = data.corporationID
        self.sr.corpicon.state = uix.UI_NORMAL
        uix.Flush(self.sr.corpicon)
        uiutil.GetLogoIcon(itemID=data.corporationID, parent=self.sr.corpicon, acceptNone=False, align=uiconst.TOALL)
        self.sr.infoicon.OnClick = self.ShowInfo
        self.sr.infoicon.state = uix.UI_NORMAL
        self.joinleaveBtn.state = (uix.UI_NORMAL if (data.channelID != None) else uix.UI_HIDDEN)
        if sm.GetService('LSC').IsJoined(self.sr.node.channelID):
            self.joinleaveBtn.SetLabel(mls.UI_CMD_LEAVE)
        else:
            self.joinleaveBtn.SetLabel(mls.UI_CMD_JOIN)



    def JoinLeaveChannel(self, *args):
        self.joinleaveBtn.state = uix.UI_DISABLED
        sm.GetService('LSC').JoinOrLeaveChannel(self.sr.node.channelID)
        self.joinleaveBtn.state = uix.UI_NORMAL



    def GetHeight(self, *args):
        (node, width,) = args
        node.height = 32
        return node.height



    def GetMenu(self):
        self._OnClick()
        if self.sr.node.Get('GetMenu', None):
            return self.sr.node.GetMenu(self)
        else:
            if self.corporationID:
                return sm.GetService('menu').GetMenuFormItemIDTypeID(self.corporationID, const.typeCorporation)
            return []



    def ShowInfo(self, *args):
        sm.GetService('info').ShowInfo(const.typeCorporation, self.sr.node.corporationID)




class CreateAdvert(uicls.Window):
    __guid__ = 'form.CreateAdvert'

    def ApplyAttributes(self, attributes):
        uicls.Window.ApplyAttributes(self, attributes)
        advert = attributes.advert
        displayMode = (attributes.displayMode or 'edit')
        self.currPage = 0
        self.displayMode = displayMode
        self.advert = advert
        self.SetWndIcon('07_08')
        windowLabel = mls.UI_GENERIC_UNKNOWN
        if (displayMode == 'edit'):
            windowLabel = mls.UI_CORP_EDITRECRUITMENTDETAILS
        elif (displayMode == 'view'):
            windowLabel = mls.UI_CORP_VIEWRECRUITMENTDETAILS
        elif (displayMode == 'add'):
            windowLabel = mls.UI_CORP_ADDRECRUITMENTDETAILS
        self.SetCaption(windowLabel)
        main = self.sr.main
        uix.Flush(self.sr.main)
        self.sr.pageWnd = {}
        self.scope = 'all'
        self.name = 'createcorpad'
        self.SetMinSize([400, 370])
        self.MakeUnResizeable()
        self.NoSeeThrough()
        uicls.Container(name='push', parent=self.sr.main, align=uiconst.TORIGHT, width=const.defaultPadding)
        uicls.Container(name='push', parent=self.sr.main, align=uiconst.TOLEFT, width=const.defaultPadding)
        self.formWnd = uicls.Container(name='form', align=uiconst.TOTOP, parent=self.sr.main)
        uicls.Frame(parent=self.formWnd)
        self.pageCount = 0
        self.retvals = {}
        self.WndReset()
        self.DisplayModeSetUp()
        return self



    def DisplayModeSetUp(self):
        if (self.displayMode == 'view'):
            self.buttons = [(mls.UI_CMD_CLOSE,
              self.OnCloseAd,
              (),
              84)]
            self.sr.buttonWnd = uix.MakeBtnGroup(self.buttons, where=self.sr.main, uniSize=1, idx=0)
            self.GotoPage(-1)
        else:
            self.buttons = [(mls.UI_CMD_CANCEL,
              self.OnCancel,
              (),
              84),
             (mls.UI_CMD_PREVIOUS,
              self.OnStepChange,
              -1,
              84),
             (mls.UI_CMD_NEXT,
              self.OnStepChange,
              1,
              84)]
            self.sr.buttonWnd = uix.MakeBtnGroup(self.buttons, where=self.sr.main, uniSize=1, idx=0)
            self.sr.buttonCancel = self.sr.buttonWnd.children[0].children[0]
            self.sr.buttonPrev = self.sr.buttonWnd.children[0].children[1]
            self.sr.buttonNext = self.sr.buttonWnd.children[0].children[2]
            self.GotoPage(0)



    def WndReset(self):
        if not hasattr(self, 'adTypesByGroupIDs'):
            self.adTypesByGroupIDs = sm.GetService('corp').GetRecruitmentAdTypes().Filter('groupID')
        if not hasattr(self, 'adGroups'):
            self.adGroups = sm.GetService('corp').GetRecruitmentAdTypes().Index('groupID')
            self.pageCount = ((2 + len(self.adGroups)) + 1)
            self.dynamicPageCount = len(self.adGroups)
            self.dynamicPageCounterTop = (2 + self.dynamicPageCount)
        if hasattr(self, 'advert'):
            if not hasattr(self, 'tempAd'):
                self.tempAd = {'desc': self.advert.description,
                 'sp': self.advert.skillPoints,
                 'typeMask': self.advert.typeMask,
                 'raceMask': self.advert.raceMask,
                 'channelID': self.advert.channelID,
                 'stationID': self.advert.stationID,
                 'days': '14'}
            if not hasattr(self, 'hasPageContent'):
                self.hasPageContent = {}
                for cnt in xrange(self.pageCount):
                    self.hasPageContent[cnt] = -1

        if not hasattr(self, 'adTypes'):
            self.adTypes = sm.GetService('corp').GetRecruitmentAdTypes()
        self.advertCaptions = []



    def GotoPage(self, n):
        uthread.new(self._GotoPage, n)



    def _GotoPage(self, n):
        try:
            self.currPage = n
            for p in self.sr.pageWnd:
                self.sr.pageWnd[p].state = uix.UI_HIDDEN

            uix.Flush(self.formWnd)
            format = []
            self.form = retfields = reqresult = errorcheck = []
            if self.sr.Get('buttonNext'):
                self.sr.buttonNext.SetLabel(mls.UI_CMD_NEXT)
            if self.sr.Get('buttonPrev'):
                self.sr.buttonPrev.state = uix.UI_NORMAL
            self.formHeight = (self.height if (getattr(self, 'formHeight', None) is None) else self.formHeight)
            if (n == 0):
                caption = mls.UI_GENERIC_GENERALINFO
                if (caption not in self.advertCaptions):
                    self.advertCaptions.append(caption)
                self.sr.buttonPrev.state = uix.UI_HIDDEN
                if (self.displayMode == 'add'):
                    format = [{'type': 'edit',
                      'label': mls.UI_GENERIC_DURATION,
                      'key': 'days',
                      'setvalue': self.tempAd['days'],
                      'intonly': [1, 30]}]
                    self.corpStations = [ (cfg.evelocations.Get(each.stationID).name, each.stationID) for each in sm.GetService('corp').GetMyCorporationsOffices() ]
                    self.corpStations.sort(lambda a, b: cmp(a[0], b[0]))
                    format.extend([{'type': 'push'}, {'type': 'combo',
                      'key': 'stationID',
                      'label': mls.UI_GENERIC_STATION,
                      'options': self.corpStations,
                      'readonly': bool((self.displayMode != 'edit')),
                      'setvalue': self.tempAd['stationID']}])
                format.extend([{'type': 'push'}, {'type': 'textedit',
                  'setvalue': self.tempAd['desc'],
                  'key': 'recruitmenttext',
                  'label': mls.UI_GENERIC_MESSAGE,
                  'required': 0,
                  'maxLength': 1000}])
                format.extend([{'type': 'push'}, {'type': 'edit',
                  'key': 'skillpoints',
                  'setvalue': self.tempAd['sp'],
                  'label': mls.UI_GENERIC_SKILLPOINTS,
                  'intonly': [0, 200000000]}])
                (self.form, retfields, reqresult, self.panels, errorcheck, refresh,) = sm.GetService('form').GetForm(format, self.formWnd)
            elif (n == 1):
                caption = ('%s %s' % (mls.UI_GENERIC_SELECT, mls.UI_GENERIC_RACE))
                if (caption not in self.advertCaptions):
                    self.advertCaptions.append(caption)
                races = [ each for each in sm.GetService('cc').GetData('races') if (each.raceID in [const.raceCaldari,
                 const.raceMinmatar,
                 const.raceGallente,
                 const.raceAmarr]) ]
                format = [{'type': 'push'}, {'type': 'header',
                  'text': ('<b>%s<b>' % mls.UI_GENERIC_RACES)}]
                for race in races:
                    selected = (False if (self.displayMode != 'add') else True)
                    if self.tempAd['raceMask']:
                        selected = ((race.raceID & self.tempAd['raceMask']) == race.raceID)
                    key = ('race_%s' % race.raceID)
                    text = Tr(race.raceName, 'character.races.raceName', race.dataID)
                    format.append({'type': 'checkbox',
                     'setvalue': selected,
                     'key': key,
                     'text': text})

                (self.form, retfields, reqresult, self.panels, errorcheck, refresh,) = sm.GetService('form').GetForm(format, self.formWnd)
            elif ((n >= 2) and (n < self.dynamicPageCounterTop)):
                index = (n - 2)
                groupIDfromIndex = self.adTypesByGroupIDs.keys()[index]
                adTypesFromGroup = self.adTypesByGroupIDs.get(groupIDfromIndex)
                adGroup = self.adGroups.get(groupIDfromIndex)
                groupName = Tr(adGroup.groupName, 'corporation.recruitmentGroups.groupName', adGroup.groupDataID)
                format.extend([{'type': 'push'}, {'type': 'header',
                  'text': ('<b>%s<b>' % groupName)}])
                for adType in adTypesFromGroup:
                    selected = (False if (self.displayMode != 'add') else True)
                    if (self.hasPageContent[n] == -1):
                        selected = True
                    elif self.tempAd['typeMask']:
                        selected = ((adType.typeMask & self.tempAd['typeMask']) == adType.typeMask)
                    key = ('type_%s' % adType.typeMask)
                    text = Tr(adType.typeName, 'corporation.recruitmentTypes.typeName', adType.dataID)
                    format.append({'type': 'checkbox',
                     'setvalue': selected,
                     'key': key,
                     'text': text})

                caption = ('%s %s' % (mls.UI_GENERIC_SELECT, groupName))
                if (caption not in self.advertCaptions):
                    self.advertCaptions.append(caption)
                (self.form, retfields, reqresult, self.panels, errorcheck, refresh,) = sm.GetService('form').GetForm(format, self.formWnd)
            else:
                caption = mls.SUMMARY
                self.advertCaptions.append(caption)
                format = self.DisplaySummary()
                (self.form, retfields, reqresult, self.panels, errorcheck, refresh,) = sm.GetService('form').GetForm(format, self.formWnd)
            self.ResizeWindow(self.form)
            self.formdata = [retfields,
             reqresult,
             errorcheck]
            self.SetTitle(n)

        finally:
            pass




    def OnComboChange(self, wnd, *args):
        if ((wnd.name == 'startStation') or (wnd.name == 'startStationDivision')):
            if (wnd.name == 'startStation'):
                self.data.startStation = wnd.GetValue()
            else:
                self.data.startStationDivision = wnd.GetValue()
            self.data.items = {}
            self.GotoPage(self.currPage)



    def OnStepChange(self, move, *args):
        if (((self.currPage + move) >= self.pageCount) and (move > 0)):
            if (self.displayMode == 'add'):
                if (eve.Message('CorpAdsConfirmCreateAdvert', None, uix.YESNO, suppress=uix.ID_YES) == uix.ID_YES):
                    self.CreateAdvert()
            else:
                if (self.displayMode == 'edit'):
                    if (eve.Message('CorpAdsConfirmEditAdvert', None, uix.YESNO, suppress=uix.ID_YES) == uix.ID_YES):
                        self.CreateAdvert()
        else:
            self.RecordSelection(self.currPage)
            self.GotoPage((self.currPage + move))



    def CreateAdvert(self):
        typeMask_ret = 0
        raceMask_ret = 0
        skillpoi_ret = self.tempAd['sp']
        descript_ret = self.tempAd['desc']
        days_ret = self.tempAd['days']
        station_ret = self.tempAd['stationID']
        for (retkey, retval,) in self.retvals.iteritems():
            if (retkey.startswith('type_') and retval):
                typeMask_ret += int(retkey[5:])
            else:
                if (retkey.startswith('race_') and retval):
                    raceMask_ret += int(retkey[5:])

        if (self.displayMode == 'edit'):
            sm.GetService('corp').UpdateRecruitmentAd(self.advert.adID, typeMask_ret, raceMask_ret, skillpoi_ret, descript_ret)
        elif (self.displayMode == 'add'):
            if (station_ret is None):
                eve.Message('NoOfficeAtStation')
                return 
            sm.GetService('corp').CreateRecruitmentAd(days_ret, station_ret, raceMask_ret, typeMask_ret, eve.session.allianceid, skillpoi_ret, descript_ret)
        self.SelfDestruct()



    def ResizeWindow(self, wnd):
        (lf, tf, wf, hf,) = wnd.GetAbsolute()
        self.formHeight = (((hf + self.sr.topParent.height) + self.sr.buttonWnd.height) + 24)
        currentPage = getattr(self, 'currPage', 0)
        self.height = max(self.formHeight, 300)



    def DisplaySummary(self):
        format = []
        if (self.displayMode == 'add'):
            days = int(self.tempAd['days'])
            text = util.FmtISK((const.corporationAdvertisementFlatFee + (const.corporationAdvertisementDailyRate * days)))
            format.extend([{'type': 'push'},
             {'type': 'header',
              'text': ('<b>%s</b>' % mls.UI_GENERIC_PRICE)},
             {'type': 'text',
              'text': text}])
            text = self.tempAd['days']
            format.extend([{'type': 'push'},
             {'type': 'header',
              'text': ('<b>%s</b>' % mls.UI_GENERIC_DAYS)},
             {'type': 'text',
              'text': text}])
        if (self.tempAd['stationID'] != None):
            text = cfg.evelocations.Get(self.tempAd['stationID']).name
        else:
            text = 'Station Missing'
        tempFormat = []
        format.extend([{'type': 'push'},
         {'type': 'header',
          'text': ('<b>%s</b>' % mls.UI_GENERIC_STATION)},
         {'type': 'text',
          'text': text}])
        text = self.tempAd['sp']
        if (text != 0):
            format.extend([{'type': 'push'},
             {'type': 'header',
              'text': ('<b>%s</b>' % mls.UI_GENERIC_SKILLPOINTS)},
             {'type': 'text',
              'text': text}])
        races = [ each for each in sm.GetService('cc').GetData('races') if (each.raceID in [const.raceCaldari,
         const.raceMinmatar,
         const.raceGallente,
         const.raceAmarr]) ]
        text = ''
        for race in races:
            selected = ((race.raceID & self.tempAd['raceMask']) == race.raceID)
            key = ('race_%s' % race.raceID)
            if selected:
                text += Tr(race.raceName, 'character.races.raceName', race.dataID)
                text += ', '

        if ((len(text) > 1) and (text[-2] == ',')):
            text = text[:-2]
        if (len(text) > 0):
            format.extend([{'type': 'push'},
             {'type': 'header',
              'text': ('<b>%s</b>' % mls.UI_GENERIC_RACES)},
             {'type': 'text',
              'text': text}])
        for index in range(0, self.dynamicPageCount):
            groupIDfromIndex = self.adTypesByGroupIDs.keys()[index]
            adTypesFromGroup = self.adTypesByGroupIDs.get(groupIDfromIndex)
            adGroup = self.adGroups.get(groupIDfromIndex)
            groupName = Tr(adGroup.groupName, 'corporation.recruitmentGroups.groupName', adGroup.groupDataID)
            text = ''
            for adType in adTypesFromGroup:
                selected = ((adType.typeMask & self.tempAd['typeMask']) == adType.typeMask)
                if selected:
                    text += Tr(adType.typeName, 'corporation.recruitmentTypes.typeName', adType.dataID)
                    text += ', '

            if ((len(text) > 1) and (text[-2] == ',')):
                text = text[:-2]
            if (len(text) > 0):
                format.extend([{'type': 'push'},
                 {'type': 'header',
                  'text': ('<b>%s</b>' % groupName)},
                 {'type': 'text',
                  'text': text}])

        text = self.tempAd['desc']
        if (len(text) > 0):
            format.extend([{'type': 'push'},
             {'type': 'push'},
             {'type': 'textedit',
              'setvalue': self.tempAd['desc'],
              'label': ('<b>%s<b>' % mls.UI_GENERIC_MESSAGE),
              'required': 0,
              'readonly': 1},
             {'type': 'push'}])
        return format



    def RecordSelection(self, currPage):
        result = sm.GetService('form').ProcessForm(self.formdata[0], self.formdata[1])
        hasContent = 0
        for (retkey, retval,) in result.iteritems():
            self.retvals[retkey] = retval
            if (retkey.startswith('type_') or retkey.startswith('race_')):
                ret = self.CalcNewMask(retkey)
                if (ret == 1):
                    hasContent = 1

        self.hasPageContent[currPage] = hasContent
        if (self.currPage == 0):
            self.tempAd['desc'] = self.retvals.get('recruitmenttext', '')
            self.tempAd['sp'] = self.retvals.get('skillpoints', '')
            if (self.displayMode == 'add'):
                self.tempAd['days'] = self.retvals.get('days', 14)
                self.tempAd['stationID'] = self.retvals.get('stationID')



    def CalcNewMask(self, maskKey):
        maskID = int(maskKey[5:])
        maskValue = int(self.retvals[maskKey])
        if maskKey.startswith('type_'):
            if ((maskID & self.tempAd['typeMask']) == maskID):
                if (maskValue == 0):
                    self.tempAd['typeMask'] = (self.tempAd['typeMask'] - maskID)
            else:
                if (maskValue == 1):
                    self.tempAd['typeMask'] = (self.tempAd['typeMask'] + maskID)
        elif ((maskID & self.tempAd['raceMask']) == maskID):
            if (maskValue == 0):
                self.tempAd['raceMask'] = (self.tempAd['raceMask'] - maskID)
        elif (maskValue == 1):
            self.tempAd['raceMask'] = (self.tempAd['raceMask'] + maskID)
        return maskValue



    def OnCancel(self, *args):
        if (self.displayMode == 'edit'):
            message = 'CorpAdsAreYouSureYouWantToCancelEdit'
        else:
            message = 'CorpAdsAreYouSureYouWantToCancel'
        if (eve.Message(message, None, uix.YESNO) == uix.ID_YES):
            self.SelfDestruct()



    def OnCloseAd(self, *args):
        self.SelfDestruct()



    def SetTitle(self, page):
        if (page == -1):
            title = mls.SUMMARY
        else:
            title = self.advertCaptions[page]
            if (self.displayMode != 'view'):
                title += (' (%s/%s)' % ((page + 1), self.pageCount))
        if (self.sr.Get('windowCaption', None) is None):
            self.sr.windowCaption = uix.GetCaption(title, self.sr.topParent, align=uix.UI_ALNONE, autoWidth=1, autoHeight=1, left=60, top=18, state=uix.UI_DISABLED, size=18)
        else:
            self.sr.windowCaption.text = title
        uiutil.Update(self)




